import UserSession from "@/UserSession";

const testStreamFunc = {
  source: null,
  eventSource: null,
  streamingFunc(params, callback) {
    let url = this.renderPathAndParams(params)
    const _this = this;
    _this.source = new EventSource(url, {
      headers: {
        Authorization: `Bearer ${UserSession.getToken()}`
      }
    });
    _this.source.onopen = function (e) {
      console.log("建立连接。。。", e);
    };
    /**
     * 客户端收到服务器发来的数据
     * 另一种写法：source.onmessage = function (event) {}
     */
    _this.source.onmessage = function (e) {
      // console.log(e);
      if (e && e.data) {
        setTimeout(() => {
          _this.onMessage(e.data, callback);
        }, 150)
      }
    };

    /**
     * 如果发生通信错误（比如连接中断），就会触发error事件
     * 或者：
     * 另一种写法：source.onerror = function (event) {}
     */
    _this.source.onerror = function (e) {
      if (e.readyState === EventSource.CLOSED) {
        console.log("连接关闭");
      } else {
        console.log(e);
      };
      _this.source.close();
    };
  },
  onMessage: function (msg, callback) {
    // console.log(msg);
    let data = JSON.parse(msg);
    // console.log(data);
    if (data.type == "final") {
      this.source.close();
    };
    if (callback) {
      callback(data)
    }
  },
  renderPathAndParams(params) {
    let url = '/cloud/llm/use/testStream';
    if (params) {
      if (url.indexOf('?') === -1) {
        url += '?' + this.getParams(params);
      } else {
        url += '&' + this.getParams(params);
      }
    };
    return url;
  },
  getParams: function (params) {
    var arr = [];
    for (var name in params) {
      arr.push(
        encodeURIComponent(name) + "=" + encodeURIComponent(params[name])
      );
    };
    return arr.join("&");
  },

}

export default testStreamFunc